package com.guozcc.bootweb.platform.common;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;

public class PageUtils {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    private static PageUtils pageUtils = new PageUtils();

    private PageUtils(){}

    public static PageUtils getInstance(){
        return pageUtils;
    }

    //分页方法(有参数)
    public <R,P> PageInfo<R> executePageByParam(int pageNum, int pageSize, P param, Function<P, List<R>> function) throws Throwable{
        try {
            log.info("开启分页");
            PageHelper.startPage(pageNum,pageSize);
            List<R> r = function.apply(param);
            return new PageInfo<R>(r);
        }finally {
            log.info("清空分页");
            PageHelper.clearPage();
        }
    }

    //分页方法(无参数)
    public <T> PageInfo<T> executePageNoParam(int pageNum, int pageSize, Supplier<List<T>> supplier) throws Throwable{
        try {
            log.info("开启分页");
            PageHelper.startPage(pageNum,pageSize);
            return new PageInfo<T>(supplier.get());
        }finally {
            log.info("清空分页");
            PageHelper.clearPage();
        }
    }
}
